package com.pomr.service.sys.Impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.sys.AgencyDao;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.City;
import com.pomr.model.sys.Coutry;
import com.pomr.model.sys.Province;
import com.pomr.model.sys.User;
import com.pomr.util.page.Page;
@Service
public class AgencyServiceImpl implements com.pomr.service.sys.AgencyService {
	@Autowired
	@Qualifier("agencyDaoImpl")
	private AgencyDao agencyDao;

	@Override
	public List<Province> getAllProvince()  throws Exception{
		List<Province> provinces = agencyDao.findByHql("from Province");
		return provinces;
	}

	@Override
	public List<City> getAllCity(String provinceId) throws Exception {
		List<City> citys = agencyDao.findByHql("from City where province.id = '"+provinceId+"'");
		return citys;
	}

	@Override
	public List<Coutry> getAllCoutry(String cityId) throws Exception {
		List<Coutry> coutys = agencyDao.findByHql("from Coutry where city.id = '"+cityId+"'");
		return coutys;
	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public boolean insertAgency(Agency agency) throws Exception {
		//TODO 机构编号按照规则编排-- 上级机构+0000 4位顺序号 触发器进行添加
		
		return agencyDao.add(agency);
	}
	
	

	@Override
	public Page<Agency> findAgencys(Agency agency, String provinceId, String cityId, String coutryId, String page) throws Exception {
		StringBuilder sb = new StringBuilder();
		String hql ="from Agency where";
		if(agency.getIdentifier()!=null){
			sb.append(" and identifier = "+agency.getIdentifier());
		}
		if(agency.getName()!=null && !"".equals(agency.getName())){
			sb.append(" and name like '"+agency.getName()+"%'");
		}
		if(coutryId!=null && !coutryId.equals("")){
			sb.append(" and coutry.id = '"+coutryId+"'");
		}else if(cityId!=null && !cityId.equals("")){
			sb.append(" and coutry.city.id = '"+cityId+"'");
		}else if(provinceId!=null && !provinceId.equals("")){
			sb.append(" and coutry.city.province.id = '"+provinceId+"'");
		}
		hql += sb.toString().replaceFirst(" and", "");
		if(hql.endsWith("where")){
			hql ="from Agency ";
		}
		Page<Agency> p = new Page<Agency>();
		int cunrrentPage = (page==null || page.equals(""))?1:Integer.valueOf(page);
		p.setCunrrentPage(cunrrentPage);
		p.setPageSize(1);
		return agencyDao.showPage(hql, "select count(1) "+hql, p);
	}
	
	

	@Override
	public boolean valiAgency(String identifier) throws Exception {
		List<Agency> agencys = agencyDao.findByHql("from Agency where identifier = '"+identifier+"' and (status !='1' or status = null)");
		if(agencys == null || agencys.size() <= 0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public List<Agency> findAgencysOfUser(User user) throws Exception {
		user = (User) agencyDao.findByHql("from User u left join fetch u.agency left join fetch u.role where u.id="+user.getId()).get(0);
		List<Agency> agencys = null;
		if(user.getRole().getId() == 1){//超级管理员--所有机构
			agencys = agencyDao.findByHql("from Agency");
		}else{
			int id = user.getAgency().getId();
			agencys = agencyDao.findByHql("from Agency where id = "+id+" or patientId = "+id);
		}
		return agencys;
	}

	@Override
	public Agency findAgencyAllInfo(Integer id) throws Exception {
		List<Agency> agencys = null;
		agencys = agencyDao.findByHql("from Agency a left join fetch a.coutry where a.id = "+id);
		if(agencys==null || agencys.size()<=0){
			return null;
		}
		return agencys.get(0);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean updateAgency(Agency agency) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("update Agency set ");
		sb.append("name = '"+agency.getName()+"',");
		if(agency.getProvince()!=null){
			sb.append("province.id = "+agency.getProvince().getId()+",");
		}
		if(agency.getCity()!=null){
			sb.append("city.id = "+agency.getCity().getId()+",");
		}
		if(agency.getCoutry()!=null){
			sb.append("coutry.id = "+agency.getCoutry().getId()+",");
		}
		sb.append("addr = '"+(agency.getAddr()==null?"":agency.getAddr())+"',");
		sb.append("tel = '"+(agency.getTel()==null?"":agency.getTel())+"',");
		sb.append("remark = '"+(agency.getRemark()==null?"":agency.getRemark())+"' ");
		sb.append("where identifier = '"+agency.getIdentifier()+"' and id="+agency.getId());
		System.out.println();
		return agencyDao.editHql(sb.toString());
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteAgencys(List<String> ids) throws Exception {
		int len = ids.size();
		if(len <= 0){
			return false;
		}
		for(int i=0;i<len;i++){
			String hql = "delete from Agency where id="+ids.get(i);
			if(!agencyDao.editHql(hql)){
				throw new Exception(ids.get(i)+"删除失败");
			}
		}
		return true;
	}

	@Override
	public Page<List<Agency>> findAgencys(Agency agency, String provinceId, String cityId, String coutryId, String page,
			String rows) throws Exception {
		StringBuilder sb = new StringBuilder();
		
		String hql ="from Agency where";
		if(agency.getIdentifier()!=null && !"".equals(agency.getIdentifier())){
			sb.append(" and identifier = '"+agency.getIdentifier()+"'");
		}
		if(agency.getName()!=null && !"".equals(agency.getName())){
			sb.append(" and name like '"+agency.getName()+"%'");
		}
		if(agency.getStatus()!=null && agency.getStatus().equals("1")){
			sb.append(" and status = '1'");
		}
		if(agency.getPatientId()!=null){
			sb.append(" and patientId = "+agency.getPatientId());
		}
		if(coutryId!=null && !coutryId.equals("")){
			sb.append(" and coutry.id = '"+coutryId+"'");
		}else if(cityId!=null && !cityId.equals("")){
			sb.append(" and coutry.city.id = '"+cityId+"'");
		}else if(provinceId!=null && !provinceId.equals("")){
			sb.append(" and coutry.city.province.id = '"+provinceId+"'");
		}
		
		hql += sb.toString().replaceFirst(" and", "");
		if(hql.endsWith("where")){
			hql ="from Agency ";
		}
		Page<List<Agency>> p = new Page<List<Agency>>();
		int cunrrentPage = (page==null || page.equals(""))?1:Integer.valueOf(page);
		p.setCunrrentPage(cunrrentPage);
		p.setPageSize(10);
		return agencyDao.showPage(hql, "select count(1) "+hql, p);
	}

	@Override
	public List<Agency> searchAgencysOfUser(User user) throws Exception {
		String ss = "select u.agency from User u where u.id="+user.getId();
		List<Agency> as = agencyDao.findByHql(ss);
//		user = (User) agencyDao.findByHql("from User u left join fetch u.agency where u.id="+user.getId()).get(0);
		String hql = "from Agency where (status=null or status != '1') and identifier like '"+as.get(0).getIdentifier()+"%' order by identifier";
		return agencyDao.findByHql(hql);
	}

	@Override
	public Page<List<Agency>> searchAgencysByCond(String identifier, String patientId, String status, String limit,
			String page) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from Agency where 1=1 ");
		if(identifier!=null && !"".equals(identifier)){
			sb.append(" and identifier like '%"+identifier+"%' ");
		}
		String hql = "from Agency where id="+patientId;
		Agency ag = (Agency) agencyDao.findByHql(hql).get(0);
		if(patientId!=null && !"".equals(patientId)){
			sb.append(" and identifier like '"+ag.getIdentifier()+"%'");
		}
		if(status!=null && !"".equals(status)){
			if(status.equals("1")){//正常
				sb.append(" and (status=null or status!='1')");
			}else if(status.equals("2")){//停用
				sb.append(" and status='1' ");
			}
		}
		sb.append("order by identifier");
		Page<List<Agency>> p = new Page<List<Agency>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		
		return agencyDao.showPage(sb.toString(), "select count(1) "+sb.toString(), p);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean changeStatus(Agency agency) throws Exception {
		String hql = "update Agency set status='"+agency.getStatus()+"' where id="+agency.getId();
		return agencyDao.editHql(hql);
	}

	@Override
	public List<Agency> searchAllAgencys() throws Exception {
		String hql = "from Agency where identifier like '3702_%' and (status != '1' or status=null)";
		return agencyDao.findByHql(hql);
	}
}
